﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Windows.Forms;

namespace DataBaseTool
{
    class MyMongoHelper
    {

        public MyMongoHelper()
        {
            
        }

        public void insert(string collectionName,BsonDocument document)
        {
            var client = getMyClient();

            var database = client.GetDatabase(data_base);


            //建立collection
            var collection = database.GetCollection<BsonDocument>(collectionName);

            collection.InsertOne(document);
            
        }

        public string getProp(string section,string key)
        {

           string value=MyMongoHelper.GetIniFileString(section, key, "", Application.StartupPath + "\\db.ini");

            return value;
        }


    

        public string user_name;
        public string pass_word;
        public string data_base;
        public string host;
        public int port;

        public MongoClient getMyClient()
        {



            //string username = getProp("dataBase", "username");


            //数据库连接字符串
            //string connectionString = getProp("dataBase", "connectionString");
            //connectionString = mongodb://root:123456@localhost:27020/admin
            //mongodb://test:123456@192.168.0.105:test
            //得到一个对象实例的连接
            string connectionString = "mongodb://" + user_name + ":" + pass_word + "@" + host + ":" +port+"/"+ data_base;
            //指定安全证书
            MongoCredential credential = MongoCredential.CreateCredential(data_base, user_name, pass_word);
            
            MongoClient mongoClient = new MongoClient(connectionString);
            


            return mongoClient;

        }



        public List<BsonDocument> read(string collectionName,BsonDocument document,int pageSize,int pageNumber)
        {
            List<BsonDocument> list = new List<BsonDocument>();


            var client = getMyClient();

            var database = client.GetDatabase(data_base);


            //建立collection
            var collection = database.GetCollection<BsonDocument>(collectionName);

            
            list=collection.Find(document).Skip(pageNumber*pageSize).Limit(pageSize).ToList<BsonDocument>();
            
            return list;


        }


        public List<BsonDocument> search(string collectionName, string key, int pageSize, int pageNumber)
        {


            List<BsonDocument> list = new List<BsonDocument>();


            var client = getMyClient();

            var database = client.GetDatabase(data_base);


            //建立collection
            var collection = database.GetCollection<BsonDocument>(collectionName);

            var stages = new List<IPipelineStageDefinition>();
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$match:{name:/"+key+"/ }}"));
            //stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$match:{AddTime:{$gt:ISODate('" + from + "'),$lt:ISODate('" + to + "')}}}"));
            //stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: \"$RootId\", count: {$sum: 1}}}"));
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$skip:" + pageSize*pageNumber + "}"));
            stages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$limit:"+pageSize+"}"));
            var pipeline = new PipelineStagePipelineDefinition<BsonDocument, BsonDocument>(stages);

            var result = collection.Aggregate(pipeline);

            list=result.ToList<BsonDocument>();

            

            return list;


        }

        
        public long count(string collectionName,BsonDocument doc)
        {

            var client = getMyClient();

            var database = client.GetDatabase(data_base);
            
            //建立collection
            var collection = database.GetCollection<BsonDocument>(collectionName);
            
            long ct = collection.CountDocuments(doc);
            
            return ct;


        }

         

        public void insertMany(string collectionName,List<BsonDocument> documents)
        {

            var client = getMyClient();

            var database = client.GetDatabase(data_base);


            //建立collection
            var collection = database.GetCollection<BsonDocument>(collectionName);

            collection.InsertMany(documents);

        }


        public void update(string collectionName,BsonDocument oldDoc,BsonDocument newDoc)
        {

            var client = getMyClient();

            var database = client.GetDatabase(data_base);


            //建立collection
            
            var collection = database.GetCollection<BsonDocument>(collectionName);

            BsonDocument doc = new BsonDocument();

            //collection.FindOneAndReplace(oldDoc, newDoc);

            collection.FindOneAndUpdate(oldDoc, newDoc);

        }



        public void delete(string collectionName,string id)
        {

            MongoClient client = getMyClient();

            IMongoDatabase mydb = client.GetDatabase(data_base);

            var document = new BsonDocument
             {
                 {"_id",new ObjectId(id)}

            };

            //声明一个Collection对象
            IMongoCollection<BsonDocument> collection = mydb.GetCollection<BsonDocument>(collectionName);


            //collection.DeleteOne()
            collection.FindOneAndDelete(document);



        }




        [System.Runtime.InteropServices.DllImport("kernel32")] //引入“shell32.dll”API文件
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal,
                                                        int size, string filePath);
        [System.Runtime.InteropServices.DllImport("kernel32")] //引入“shell32.dll”API文件
        public static extern bool WritePrivateProfileString(string section, string key, string val, string filepath);

        public static string GetIniFileString(string section, string key, string def, string filePath)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(section, key, def, temp, 1024, filePath);
            return temp.ToString();
        }

       













    }
}
